package com.example.yam.greenapp;

import android.app.ListActivity;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static android.R.attr.bitmap;
import static android.R.attr.handle;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link IndexFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link IndexFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class IndexFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    //数据
    private static final String TAG = "IndexFragment";


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private View view;//本界面

    private Button searchBut;
    private EditText searchEt;
    private Button B01;
    private Button B02;
    private Button B03;
    private Button B04;

    private TextView  T01;
    private TextView  T02;
    private TextView  T03;
    private TextView  T04;

    private ListView plist;//排行榜
    private RollPagerView rollPagerView;
    //适配器
    private List<Goods> goodsList = new ArrayList<Goods>();//list


    public IndexFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment IndexFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static IndexFragment newInstance(String param1, String param2) {
        IndexFragment fragment = new IndexFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // 设置view
        this.view=inflater.inflate(R.layout.fragment_index, container,false);
        this.plist = (ListView) view.findViewById(R.id.plist); //初始化排行榜组件
        this.plist.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent it = new Intent(getActivity(),DetailActivity.class);
                it.putExtra("id",goodsList.get(position).getId());
                Log.v(TAG,goodsList.get(position).getId());
                startActivity(it);
            }
        });
        this.rollPagerView = (RollPagerView) view.findViewById(R.id.rollpageview); //轮播图--使用开源组件
        //设置数据
        getMessage();//添加数据

        //初始化按钮和Tv组件
        initBT();

        Log.d(TAG,"Index布局oncreateView调用成功");
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    //初始化按钮和TextView组件
    public void initBT(){

        this.searchEt = (EditText) this.view.findViewById(R.id.index_Esearch);
        this.searchBut = (Button) this.view.findViewById(R.id.index_Bsearch);
        this.searchBut.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                String ss = searchEt.getText().toString();
                if(TextUtils.isEmpty(ss)){
                    Toast.makeText(getActivity(),"搜索内容不能为空!!",Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent it = new Intent(getActivity(),SlistActivity.class);
                it.putExtra("key",ss);
                startActivity(it);
            }
        });
        this.B01 = (Button)this.view.findViewById(R.id.B01);
        this.B02 = (Button)this.view.findViewById(R.id.B02);
        this.B03 = (Button)this.view.findViewById(R.id.B03);
        this.B04 = (Button)this.view.findViewById(R.id.B04);

        this.T01 = (TextView) this.view.findViewById(R.id.T01);
        this.T02 = (TextView) this.view.findViewById(R.id.T02);
        this.T03 = (TextView) this.view.findViewById(R.id.T03);
        this.T04 = (TextView) this.view.findViewById(R.id.T04);

        this.T01.setText("测试一下");
    }
    private void getMessage(){//获取首页信息
        VolleyGetString(MyApplication.localhost+"Green/index.php/indexg/index");
    }
    //使用volley获取数据
    private void VolleyGetString(String url){
        RequestQueue mQueue = MyApplication.getHttpQueue();
        Log.d(TAG, "开始了");
        StringRequest stringRequest = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {//正确搜索到数据
                        parseJSONobject(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, error.getMessage(), error);
            }
        });
        mQueue.add(stringRequest);
    }
    //json解析
    private void parseJSONobject(String ss){
        try{
           // Log.d(TAG,"数据是"+ss);
          JSONObject jsb = new JSONObject(ss);
            JSONArray jsonArray=(JSONArray) new JSONArray(jsb.getString("phblist"));
            //排行榜数据布置
            for(int i=0;i<jsonArray.length();i++){
                JSONObject jb=jsonArray.getJSONObject(i);
                String pic=MyApplication.localhost+"Green/public/photo/"+jb.getString("pic");
                Log.v(TAG,pic);
                Log.v(TAG,jb.getString("name"));
                Goods g = new Goods(jb.getString("id"),pic, jb.getString("name"), jb.getString("lintro"), "/"+jb.getString("danwei"), jb.getString("price")+"元");
                goodsList.add(g);
            }
            GoodsAdapter goodsAdapter = new GoodsAdapter(super.getActivity(),R.layout.goodslist,goodsList);
            this.plist.setAdapter(goodsAdapter);
            //分类数据设置
            JSONArray fnames=(JSONArray) new JSONArray(jsb.getString("clist"));
            Log.d(TAG,"数据是"+fnames.toString());

            //初始化
            MyApplication.burl.clear();
            JSONObject jb1=fnames.getJSONObject(0);
            Classfy classfy0 = new Classfy(jb1.getString("id"),jb1.getString("name"));
            T01.setText(jb1.getString("name"));
            MyApplication.burl.add(classfy0);

            jb1=fnames.getJSONObject(1);
            Classfy classfy1 = new Classfy(jb1.getString("id"),jb1.getString("name"));
            T02.setText(jb1.getString("name"));
            MyApplication.burl.add(classfy1);

            jb1=fnames.getJSONObject(2);
            Classfy classfy2 = new Classfy(jb1.getString("id"),jb1.getString("name"));
            T03.setText(jb1.getString("name"));
            MyApplication.burl.add(classfy2);

            jb1=fnames.getJSONObject(3);
            Classfy classfy3 = new Classfy(jb1.getString("id"),jb1.getString("name"));
            T04.setText(jb1.getString("name"));
            MyApplication.burl.add(classfy3);

            AddButClick();

            //轮播图数据设置
            JSONArray rollview=(JSONArray) new JSONArray(jsb.getString("display"));
            Log.d(TAG,"数据是"+rollview.toString());
            MyApplication.piclist.clear();//清空数据
            int len=rollview.length();
            for(int i=0;i<len;i++){
                JSONObject jb=rollview.getJSONObject(i);
                String path=jb.getString("pic").replace("thumb_","");
                String pic=MyApplication.localhost+"Green/public/photo/"+path;
                Log.v(TAG,"路径是"+pic);
                MyApplication.setRollViewUrl(pic);
            }
            RollPageViewSet();//轮播图设置
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //按钮监听事件添加
    public void AddButClick(){
        this.B01.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {//传递路径
                Intent it = new Intent();
                String cid=MyApplication.burl.get(0).getId();
                String cname=MyApplication.burl.get(0).getName();
                it.putExtra("cid", cid);
                it.putExtra("cname",cname);
                it.setClass(getActivity(), ClistActivity.class);

                startActivity(it);
            }
        });
        this.B02.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {//传递路径
                Intent it = new Intent();
                String cid=MyApplication.burl.get(1).getId();
                String cname=MyApplication.burl.get(1).getName();
                it.putExtra("cid", cid);
                it.putExtra("cname",cname);
                it.setClass(getActivity(), ClistActivity.class);

                startActivity(it);
            }
        });
        this.B03.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {//传递路径
                Intent it = new Intent();
                String cid=MyApplication.burl.get(2).getId();
                String cname=MyApplication.burl.get(2).getName();
                it.putExtra("cid", cid);
                it.putExtra("cname",cname);

                it.setClass(getActivity(), ClistActivity.class);

                startActivity(it);
            }
        });
        this.B04.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {//传递路径
                Intent it = new Intent();
                String cid=MyApplication.burl.get(3).getId();
                String cname=MyApplication.burl.get(3).getName();
                it.putExtra("cid", cid);
                it.putExtra("cname",cname);
                it.setClass(getActivity(), ClistActivity.class);

                startActivity(it);
            }
        });


    }
    //轮播图设置
    public void RollPageViewSet(){
        this.rollPagerView.setPlayDelay(2000);
        this.rollPagerView.setAnimationDurtion(500);
        Log.v(TAG,"长度是"+MyApplication.piclist.size());
        this.rollPagerView.setAdapter(new RollPageViewAdapter());//设置适配器
    }
    //适配器
    private class RollPageViewAdapter extends StaticPagerAdapter{
        //创建ImageLoader,用于将图片存入缓存和从缓存中取出图片
        private List<String> urlList=MyApplication.getPiclist();
        ImageLoader mImageLoader= MyApplication.getmImageLoader();
        @Override
        public View getView(ViewGroup container, int position) {

            ImageView imageView=new ImageView(container.getContext());
            Log.v(TAG,"路径"+MyApplication.piclist.get(position));
            mImageLoader.get(urlList.get(position),ImageLoader.getImageListener(imageView,R.drawable.pic02, R.drawable.pic02));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            return imageView;
        }
        @Override
        public int getCount() {
          return urlList.size();
        }
    }
}